{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# The JSON Representation of Refrigeration Cycle Flowsheet\n",
    "\n",
    "* **Textual Representation of VCR Cycle Flowsheet**.\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "\n",
    "## 1 JSON\n",
    "\n",
    "[JSON (JavaScript Object Notation)](http://json.org/) is a `lightweight data interchange` format inspired by [JavaScript](https://en.wikipedia.org/wiki/JavaScript) **object literal syntax**.\n",
    "\n",
    "JSON is most commonly used to make structured text representations of data including primitive types such as numbers and text, along with structured types such as lists and dictionaries. \n",
    "\n",
    "JSON was originally designed to provide text representations for data in the JavaScript language. \n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "\n",
    "\n",
    "### 1.1 `JSON` is built on `two` structures:\n",
    "\n",
    "1. A collection of **name/value** pairs. \n",
    "\n",
    "   * In various languages, this is realized as an `object`, `record`, `struct`, **dictionary**, `hash table`, `keyed list`, or `associative array`. \n",
    "   \n",
    "    <b style=\"color:blue\">Python: dictionary</b>\n",
    "   \n",
    "\n",
    "2. An **ordered list** of values.\n",
    "\n",
    "  * In most languages, this is realized as an `array`, `vector`, **list**, or `sequence`.\n",
    "  \n",
    "     <b style=\"color:blue\">Python:list</b>\n",
    "\n",
    "### 1.2  An object\n",
    "\n",
    " An `object` is an `unordered` set of  `name/value` pairs.\n",
    "\n",
    "* An `object` begins with `{` (left brace) and ends with `}` (right brace).\n",
    "\n",
    "```json\n",
    "{\n",
    "  name1:value2,\n",
    "  name2:value2\n",
    "    \n",
    " }\n",
    "```\n",
    "\n",
    "* **name/value** pairs.\n",
    "\n",
    "   * The **name/value** pairs are `separated` by `, `(comma)\n",
    "\n",
    "   * Each `name` is followed by `:` (colon) \n",
    "\n",
    "   * The `value` can be a `string` in double quotes(\"), or a `number`, or `true` or `false` or `null`, or an `object` or an `array`，These structures can be **nested**.\n",
    "      \n",
    "      \n",
    "* The **string** is a sequence of zero or more `Unicode` characters, wrapped in `double` quotes(`\"`), using backslash escapes(`\\`)\n",
    "\n",
    "\n",
    "* The **character** is represented as a `single` character string. \n",
    "\n",
    "\n",
    "* A **number** is very much like a `C`number, `except` that the `octal and hexadecimal` formats are not used.\n",
    "\n",
    "###  1.3 An array\n",
    "\n",
    " An `array` is an `ordered` collection of **values**\n",
    " \n",
    "* An array begins with `[` (left bracket) and ends with `]` (right bracket).\n",
    "\n",
    "```\n",
    "[ \n",
    "\n",
    " jsonobject1,\n",
    " jsonobject2\n",
    " \n",
    "]\n",
    "```\n",
    "\n",
    "* Values are separated by `,` (comma).\n",
    "\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 2  The  `json` of VCR Cycle Flowsheet\n",
    "\n",
    "The [An ideal vapor-compression refrigeration cycle：Example 7.2-3 ](./Unit4-2-RefrigerationCycle_OOP.ipynb) is used as the example to show the forms of `JSON` items \n",
    "\n",
    "![Example 7.2-3](./img/vcr/vcr-cycle.jpg)\n",
    "\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "#### The json object of port\n",
    "\n",
    "```json\n",
    "      {\n",
    "        \"t\": 0,\n",
    "         \"x\": 1,\n",
    "        \"mdot\": 0.08\n",
    "       }\n",
    "```\n",
    "\n",
    "#### The json object of device\n",
    "\n",
    "```json\n",
    "       {\n",
    "            \"name\": \"Compressor\",\n",
    "            \"devtype\": \"COMPRESSOR\",\n",
    "            \"iPort\": {\n",
    "                \"t\": 0,\n",
    "                \"x\": 1,\n",
    "                \"mdot\": 0.08\n",
    "              },\n",
    "            \"oPort\": {},\n",
    "            \"ef\": 1.0\n",
    "        }\n",
    "```\n",
    "#### The json object of Connection node and pairs\n",
    "\n",
    "The json object of Connection node\n",
    "\n",
    "```json\n",
    "       {\n",
    "                \"devname\": \"Compressor\",\n",
    "                \"port\": \"oPort\"\n",
    "       }\n",
    "\n",
    "```\n",
    "\n",
    "The Connection node pairs\n",
    "\n",
    "```json\n",
    "   [\n",
    "       {\n",
    "                \"devname\": \"Compressor\",\n",
    "                \"port\": \"oPort\"\n",
    "            },\n",
    "            {\n",
    "                \"devname\": \"Condenser\",\n",
    "                \"port\": \"iPort\"\n",
    "            }  \n",
    "   ]\n",
    "```\n",
    "\n",
    "\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "**The json of VCR Cycle Flowsheet**\n",
    "\n",
    "```json\n",
    "{\n",
    "    \"type\": \"REFRIGERATION\",\n",
    "    \"name\": \"The Ideal VCR Example 7.2-3\",\n",
    "    \"components\": [\n",
    "        the list of device\n",
    "    ],\n",
    "    \"connectors\": [\n",
    "        the list of Connection node pairs\n",
    "    ]\n",
    "}\n",
    "```"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "**The json of Example 7.2-3**\n",
    "\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Overwriting ./data/ivcr723.json\n"
     ]
    }
   ],
   "source": [
    "%%file ./data/ivcr723.json\n",
    "{\n",
    "  \n",
    "    \"name\": \"The Ideal VCR Example 7.2-3\",\n",
    "    \"components\": [\n",
    "        {\n",
    "            \"name\": \"Compressor\",\n",
    "            \"devtype\": \"COMPRESSOR\",\n",
    "            \"iPort\": {\n",
    "                \"t\": 0,\n",
    "                \"x\": 1,\n",
    "                \"mdot\": 0.08\n",
    "            },\n",
    "            \"oPort\": {},\n",
    "            \"ef\": 1.0\n",
    "        },\n",
    "        {\n",
    "            \"name\": \"Condenser\",\n",
    "            \"devtype\": \"CONDENSER\",\n",
    "            \"iPort\": {},\n",
    "            \"oPort\": {\n",
    "                \"t\": 26,\n",
    "                \"x\": 0\n",
    "            }\n",
    "        },\n",
    "        {\n",
    "            \"name\": \"ExpansionValve\",\n",
    "            \"devtype\": \"EXPANSIONVALVE\",\n",
    "            \"iPort\": {},\n",
    "            \"oPort\": {}\n",
    "        },\n",
    "        {\n",
    "            \"name\": \"Evaporator\",\n",
    "            \"devtype\": \"EVAPORATOR\",\n",
    "            \"iPort\": {},\n",
    "            \"oPort\": {}\n",
    "        }\n",
    "    ],\n",
    "    \"connectors\": [\n",
    "        [\n",
    "            {\n",
    "                \"devname\": \"Compressor\",\n",
    "                \"port\": \"oPort\"\n",
    "            },\n",
    "            {\n",
    "                \"devname\": \"Condenser\",\n",
    "                \"port\": \"iPort\"\n",
    "            }\n",
    "        ],\n",
    "        [\n",
    "            {\n",
    "                \"devname\": \"Condenser\",\n",
    "                \"port\": \"oPort\"\n",
    "            },\n",
    "            {\n",
    "                \"devname\": \"ExpansionValve\",\n",
    "                \"port\": \"iPort\"\n",
    "            }\n",
    "        ],\n",
    "        [\n",
    "            {\n",
    "                \"devname\": \"ExpansionValve\",\n",
    "                \"port\": \"oPort\"\n",
    "            },\n",
    "            {\n",
    "                \"devname\": \"Evaporator\",\n",
    "                \"port\": \"iPort\"\n",
    "            }\n",
    "        ],\n",
    "        [\n",
    "            {\n",
    "                \"devname\": \"Evaporator\",\n",
    "                \"port\": \"oPort\"\n",
    "            },\n",
    "            {\n",
    "                \"devname\": \"Compressor\",\n",
    "                \"port\": \"iPort\"\n",
    "            }\n",
    "        ]\n",
    "    ]\n",
    "}"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 3 The Python Object of VCR Cycle\n",
    "\n",
    "### 3.1 Json to Python Object\n",
    "**json.loads**\n",
    "\n",
    "Python3: https://docs.python.org/3/library/json.html\n",
    "\n",
    "```python\n",
    "json.loads(s, *, encoding=None, cls=None, object_hook=None, parse_float=None, parse_int=None, parse_constant=None, object_pairs_hook=None, **kw)\n",
    "```\n",
    "Deserialize s (a str, bytes or bytearray instance containing a JSON document) to a Python object using this conversion table.\n",
    "\n",
    ">\n",
    ">pprint, Data pretty printer: https://docs.python.org/3/library/pprint.html\n",
    ">\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "{'components': [{'devtype': 'COMPRESSOR',\n",
      "                 'ef': 1.0,\n",
      "                 'iPort': {'mdot': 0.08, 't': 0, 'x': 1},\n",
      "                 'name': 'Compressor',\n",
      "                 'oPort': {}},\n",
      "                {'devtype': 'CONDENSER',\n",
      "                 'iPort': {},\n",
      "                 'name': 'Condenser',\n",
      "                 'oPort': {'t': 26, 'x': 0}},\n",
      "                {'devtype': 'EXPANSIONVALVE',\n",
      "                 'iPort': {},\n",
      "                 'name': 'ExpansionValve',\n",
      "                 'oPort': {}},\n",
      "                {'devtype': 'EVAPORATOR',\n",
      "                 'iPort': {},\n",
      "                 'name': 'Evaporator',\n",
      "                 'oPort': {}}],\n",
      " 'connectors': [[{'devname': 'Compressor', 'port': 'oPort'},\n",
      "                 {'devname': 'Condenser', 'port': 'iPort'}],\n",
      "                [{'devname': 'Condenser', 'port': 'oPort'},\n",
      "                 {'devname': 'ExpansionValve', 'port': 'iPort'}],\n",
      "                [{'devname': 'ExpansionValve', 'port': 'oPort'},\n",
      "                 {'devname': 'Evaporator', 'port': 'iPort'}],\n",
      "                [{'devname': 'Evaporator', 'port': 'oPort'},\n",
      "                 {'devname': 'Compressor', 'port': 'iPort'}]],\n",
      " 'name': 'The Ideal VCR Example 7.2-3'}\n"
     ]
    }
   ],
   "source": [
    "import json\n",
    "import pprint\n",
    "\n",
    "filename='./data/ivcr723.json'\n",
    "with open(filename, 'r') as f:\n",
    "     vcr = json.loads(f.read())\n",
    "pprint.pprint(vcr)  \n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 3.2 The Python Object of VCR Cycle\n",
    "\n",
    "The Python Object \n",
    "```python\n",
    "{  'name': 'RankineCycleName',\n",
    "   \"components\"[{},{}],\n",
    "   \"connectors\":[((),()),((),())...]\n",
    "} \n",
    "```\n",
    "\n",
    "```python\n",
    " 'connectors': [[{'devname': 'Compressor', 'port': 'oPort'},\n",
    "                 {'devname': 'Condenser', 'port': 'iPort'}],\n",
    "                [{'devname': 'Condenser', 'port': 'oPort'},\n",
    "                 {'devname': 'ExpansionValve', 'port': 'iPort'}],\n",
    "                [{'devname': 'ExpansionValve', 'port': 'oPort'},\n",
    "                 {'devname': 'Evaporator', 'port': 'iPort'}],\n",
    "                [{'devname': 'Evaporator', 'port': 'oPort'},\n",
    "                 {'devname': 'Compressor', 'port': 'iPort'}]],\n",
    "\n",
    "```\n",
    "\n",
    "We have to convert the list of dict object `connectors` obtained from ` vcr = json.loads(f.read())`\n",
    "```python\n",
    "[{'devname': 'Compressor', 'port': 'oPort'},\n",
    "                 {'devname': 'Condenser', 'port': 'iPort'}]\n",
    "```\n",
    "\n",
    "to the tuple of tuple\n",
    "\n",
    "```python\n",
    " \"connectors\":[((),()),((),())...]\n",
    "```        \n",
    "```python\n",
    "\n",
    "cycle[\"connectors\"] = [\n",
    "    ((\"Compressor\", \"oPort\"), (\"Condenser\", \"iPort\")),\n",
    "    ((\"Condenser\", \"oPort\"), (\"ExpansionValve\", \"iPort\")),\n",
    "    ((\"ExpansionValve\", \"oPort\"), (\"Evaporator\", \"iPort\")),\n",
    "    ((\"Evaporator\", \"oPort\"), (\"Compressor\", \"iPort\"))]\n",
    "```"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "{'components': [{'devtype': 'COMPRESSOR',\n",
      "                 'ef': 1.0,\n",
      "                 'iPort': {'mdot': 0.08, 't': 0, 'x': 1},\n",
      "                 'name': 'Compressor',\n",
      "                 'oPort': {}},\n",
      "                {'devtype': 'CONDENSER',\n",
      "                 'iPort': {},\n",
      "                 'name': 'Condenser',\n",
      "                 'oPort': {'t': 26, 'x': 0}},\n",
      "                {'devtype': 'EXPANSIONVALVE',\n",
      "                 'iPort': {},\n",
      "                 'name': 'ExpansionValve',\n",
      "                 'oPort': {}},\n",
      "                {'devtype': 'EVAPORATOR',\n",
      "                 'iPort': {},\n",
      "                 'name': 'Evaporator',\n",
      "                 'oPort': {}}],\n",
      " 'connectors': [[('Compressor', 'oPort'), ('Condenser', 'iPort')],\n",
      "                [('Condenser', 'oPort'), ('ExpansionValve', 'iPort')],\n",
      "                [('ExpansionValve', 'oPort'), ('Evaporator', 'iPort')],\n",
      "                [('Evaporator', 'oPort'), ('Compressor', 'iPort')]],\n",
      " 'name': 'The Ideal VCR Example 7.2-3'}\n"
     ]
    }
   ],
   "source": [
    "import json\n",
    "import pprint\n",
    "def create_didevtypectcycle_from_jsonfile(filename):\n",
    "    \"\"\" create dict cycle from json file\"\"\"\n",
    "    with open(filename, 'r') as f:\n",
    "        dictcycle = json.loads(f.read())\n",
    "\n",
    "    # convert the list of dict object  to  the tuple of tuple\n",
    "    for itemtuples in dictcycle[\"connectors\"]:\n",
    "        for i in range(len(itemtuples)):\n",
    "            itemtuples[i] = (itemtuples[i][\"devname\"], itemtuples[i][\"port\"])\n",
    "    return dictcycle\n",
    "\n",
    "filename='./data/ivcr723.json'\n",
    "thedictcycle=create_didevtypectcycle_from_jsonfile(filename)\n",
    "pprint.pprint(thedictcycle)  "
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Reference\n",
    "\n",
    "* VCCE https://github.com/PySEE/SimVCCE\n",
    "\n",
    "\n",
    "\n",
    "* [Python3: json — JSON encoder and decoder](https://docs.python.org/3/library/json.html)\n",
    "\n",
    "* [pymotw: json — JavaScript Object Notation](https://pymotw.com/3/json/index.html)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.8.7"
  },
  "latex_envs": {
   "LaTeX_envs_menu_present": true,
   "autoclose": false,
   "autocomplete": true,
   "bibliofile": "biblio.bib",
   "cite_by": "apalike",
   "current_citInitial": 1,
   "eqLabelWithNumbers": true,
   "eqNumInitial": 1,
   "hotkeys": {
    "equation": "Ctrl-E",
    "itemize": "Ctrl-I"
   },
   "labels_anchors": false,
   "latex_user_defs": false,
   "report_style_numbering": false,
   "user_envs_cfg": false
  },
  "toc": {
   "base_numbering": 1,
   "nav_menu": {},
   "number_sections": false,
   "sideBar": true,
   "skip_h1_title": false,
   "title_cell": "Table of Contents",
   "title_sidebar": "Contents",
   "toc_cell": false,
   "toc_position": {
    "height": "calc(100% - 180px)",
    "left": "10px",
    "top": "150px",
    "width": "165px"
   },
   "toc_section_display": true,
   "toc_window_display": true
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
